/**
 * Sensor Network Development Kit for 1-Wire Network (SeN)
 * Version : 0.1
 * Revision date : 2008-10-13
 * Author: Dubravko Penezic, dpenezic@gmail.com
 */

package owExample;

import java.util.Date;
import java.util.Enumeration;
import java.io.*;

import com.dalsemi.onewire.*;
import com.dalsemi.onewire.adapter.*;
import com.dalsemi.onewire.container.*;
import owLib.*;
import owSensor.*;
import utilityLib.*;

/**
 * HBBarometer class is example how to read and display data from Hobby-Boards Barometer board
 * http://www.hobby-boards.com/catalog/product_info.php?cPath=25_28&products_id=38
 * 
 * On same time it also show how to do that with same schematic using DS chips and 1-Wire network
 * 
 * Version : 0.1.1
 * Revision date : 2008-10-22
 * 
 * @author Dubravko Penezic, dpenezic@gmail.com
 *
 * Based on T. Bitson, SimpleWeather, SimpleWeather.java, 2007
 */

public class HBBarometer
{
  
  private DSPortAdapter adapter;
  private static OWConf c;
  public OneWireContainer[] owd;
  public OWDevice device;
  
  // Instance of sensors class
  public BaroSensor bs;
  
  public String[] hAddress;
  public String[] hPorts;
  
  public AtmospericPressureTransformer apt;
  
  // set calib to true if you calibrate your device, also jumper JP1 must be in position 1-2, return it in
  // position 2-3 for normal operation
  public boolean calib = false;

  /**
   *  Finding and init communication adapter and reset 1-Wire bus 
   */ 
  public HBBarometer()
  {
    // get the 1-wire adapter
    try
    {
      // get an instance of the 1-Wire adapter
      adapter = OneWireAccessProvider.getAdapter(c.ONE_WIRE_ADAPTER_TYPE, c.ONE_WIRE_SERIAL_PORT);
      if (adapter != null)
      {
        System.out.println("Found Adapter: " + adapter.getAdapterName() +
                " on Port " + adapter.getPortName());
      }
      else
      {
        System.out.println("Error: Unable to find 1-Wire adapter!");
        System.exit(1);
      }
         
      // reset the 1-Wire bus
      resetBus();

      // set parameters for 1-Wire devices and path to devices on 1-Wire network
      
      // set hub/coupler hex address to 1-Wire device
      // more then one do {"hex_string_address_top", "hex_string_lower",...}
      // if no coupler/hub on network set {"root"}
      hAddress = new String[]{"6500000003DFD81F"};
      // set hub/coupler port to 1-Wire device ("main", "aux"}
      // more then one do {"port_string_top", "port_string_lower",...} corresponding with hex string address of hub/coupler
      // if no coupler/hub on network set {"main"}      
      hPorts = new String[]{"aux"};
      //create instance of device 
      // first parameter is hex string address of device
      device = new OWDevice("FA000000C1AC4D26",hAddress,hPorts);
      
      // make instance of temperature DS1820/DS18S20/DS1920 device
      bs = new BaroSensor(adapter,device);
      
      apt = new AtmospericPressureTransformer();
      
    }
    catch (OneWireException e)
    {
      System.out.println("Error Finding Adapter: "+ e);
      System.exit(1);
    }
    
  }
    
  /**
   * mainLoop is thread service , do loop checking if minute is change
   */   
  public void mainLoop()
  {
    Date date = new Date();
    int minute, lastMinute = -99;
    boolean quit = false;
    InputStreamReader in = new InputStreamReader(System.in);
    OWHub h;
   
    while(!quit)
    {
      // sleep for 1 second
      try
      {
        Thread.sleep(1000);
        if(calib) Thread.sleep(2000);
      }
      catch (InterruptedException e)
      {}
      
      // check current time
      date.setTime(System.currentTimeMillis());
      minute = date.getMinutes();
      
      
      // only loop if a minute is change
      if ((minute != lastMinute) || calib)
      {
    	if(! calib){
        System.out.println("------------------------------------------------------------");
        System.out.println("I  Time = " + date);
        System.out.println("------------------------------------------------------------");
    	}
        try
        {

           adapter.beginExclusive(true);

           // clear any previous search restrictions
           adapter.setSearchAllDevices();
           adapter.targetAllFamilies();
           adapter.setSpeed(adapter.SPEED_REGULAR);
           
           
           if(calib) bs.calibration(123);
           else {

        	 // read barometric pressure
             double bp = bs.getPressure();
             // display pressure and use AtmospericPressureTransformer class
             System.out.println("Barometric Pressure : "+bp+" kPa   "+apt.fromkPatomb(bp)+" mb   "+apt.fromkPatoinHg(bp)+" inHg");
        	   
           }
           adapter.endExclusive();

        }
        catch (Exception e)
        {
           System.out.println(e);
        }
        
        System.out.println("\n");
        
        // update the time
        lastMinute = minute;
      }
      
      // development use only - check for 'q' key press
      try
      {
        if (in.ready())
          if (in.read() == 'q')
          {
            quit = true;
        
            try
            {
              adapter.freePort();
            }
            catch (OneWireException e)
            {
              System.out.println("Error Finding Adapter: "+ e);
            }
			   }
      }
      catch (IOException e)
      { } 
    }
  }
  
  /**
   * main start main program and test input parameters if exist, start thread service
   *    
   * @param args
   */  
  public static void main(String[] args)
  {
    System.out.println("Starting " + c.VERSION);
    
    if (args.length != 0)
    {
      if (args[0].equals("-d"))
      {
        System.out.println("debug on");
        c.debugFlag = true;
      }
    }
    
    try
    {
    	
      HBBarometer loopServer   = new HBBarometer();
      
      // call the main program loop
      loopServer.mainLoop();
    }
    catch(Throwable t)
    {
      System.out.println("Exception: Main() " + t);
    }
    finally
    {
      System.out.println(c.VERSION+" Stopped");
      System.exit(0);
    }
  }
  
  /**
   * resetBus method try to reset 1-Wire bus
   *     
  */  
  private void resetBus() // reset the 1-wire bus
  {
    System.out.println("Resetting 1-Wire bus");
    
    try
    {
      int result = adapter.reset();
      
      if (result == 0)
        System.out.println("Warning: Reset indicates no Device Present");
      if (result == 3)
        System.out.println("Warning: Reset indicates 1-Wire bus is shorted");
    }
    catch (OneWireException e)
    {
      System.out.println("Exception Resetting the bus: " + e);
    }
  }

}

